package com.wx.service.imp;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import com.wx.dao.CheckGroupDao;
import com.wx.entity.PageResult;
import com.wx.entity.QueryPageBean;
import com.wx.pojo.CheckGroup;
import com.wx.pojo.CheckItem;
import com.wx.service.CheckGroupService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
@Service(interfaceClass = CheckGroupService.class)
@Transactional
public class CheckGroupServiceImp implements CheckGroupService {
    @Autowired
    private CheckGroupDao checkGroupDao;

    /**
     * 分页查询
     * @param queryPageBean
     * @return
     */
    @Override
    public PageResult findAllGroup(QueryPageBean queryPageBean) {
        Integer pageSize = queryPageBean.getPageSize();
        Integer currentPage = queryPageBean.getCurrentPage();
        String queryString = queryPageBean.getQueryString();
        PageHelper.startPage(currentPage,pageSize);
        List<CheckGroup> allGroup = checkGroupDao.findAllGroup(queryString);
        PageInfo<CheckGroup> pageInfo = new PageInfo<>(allGroup);
        long total = pageInfo.getTotal();
        PageResult pageResult = new PageResult(total, allGroup);
        return pageResult;
    }

    @Override
    public CheckGroup findGroupById(Integer id) {
        // 查询出要修改的检查项信息
        CheckGroup groupById = checkGroupDao.findGroupById(id);
        groupById.setId(id);
        return groupById;
    }

    @Override
    public void addGroup(CheckGroup checkGroup,Integer[] ids) {
        checkGroupDao.addGroup(checkGroup);

        // 把数组中的数据添加到中间表中
        for (Integer id : ids) {
            checkGroupDao.addCheckgroupCheckitem(checkGroup.getId(),id);
        }
    }

    @Override
    public void deleteGroupById(Integer id) {
            // 删除检查组中的信息
            checkGroupDao.deleteGroupById(id);
            // 删除中间表中的信息
        checkGroupDao.deleteCheckgroupCheckitem(id);
    }

    @Override
    public void updateGroupById(CheckGroup checkGroup) {

    }

    @Override
    public  String []  findItemsById(Integer id) {
        CheckGroup itemsById = checkGroupDao.findItemsById(id);
        List<CheckItem> items = itemsById.getCheckItems();
        // 把查询到的所有的检查项的code封装到一个数组中
        int length = items.size();
        String [] arrs=new String[length];
        for (int i = 0; i < items.size(); i++) {
            java.lang.String code = items.get(i).getCode();
            arrs[i]=code;
        }
        return arrs;
    }

    @Override
    public void modify(CheckGroup checkGroup, Integer[] items) {
        // 修改中间表中数据与检查组中数据
        // 先删除中间表数据
        Integer gid = checkGroup.getId();
        checkGroupDao.deleteAllMidtable(gid);
        // 循环添加数据
        for (Integer item : items) {
            checkGroupDao.addCheckgroupCheckitem(gid,item);
        }
    }
}
